<template>
  <el-dialog
      v-model="accountStore.showLoginDialog"
      width="600px"
      :draggable="true"
      @close="handleClose"
      :close-on-click-modal="false"
      style="border-radius: 5px"
  >
    <template #header>
      <div class="header">
        <h1>登录发现更多精彩</h1>
      </div>
    </template>
    
    <template #default>
      <div class="default">
        <div class="account-login">
          <header>{{ isRegister ? '验证码注册/登录' : '密码登录' }}</header>
          <div class="login-form">
            <el-form :model="formData" :rules="rules" ref="form">
              <!--               邮箱input-->
              <el-form-item prop="email">
                <el-input
                    type="text"
                    v-model="formData.email"
                    placeholder="请输入邮箱/手机号"
                    maxlength="30"
                >
                  <template #prefix>
                    <svg class="icon">
                      <use xlink:href="#icon-youxiang"></use>
                    </svg>
                  </template>
                </el-input>
              </el-form-item>
              <!--密码input-->
              <el-form-item v-if="!isRegister" prop="password">
                <el-input
                    :type="showPassword?'text':'password'"
                    v-model="formData.password"
                    placeholder="请输入密码"
                    maxlength="30"
                    minlength="6"
                >
                  <template #prefix>
                    <svg class="icon">
                      <use xlink:href="#icon-mima"></use>
                    </svg>
                  </template>
                  <template #suffix>
                    <svg class="icon" v-if="showPassword && !isRegister && formData.password.length"
                         @click="showPassword = !showPassword">
                      <use xlink:href="#icon-xianshimima"></use>
                    </svg>
                    <svg class="icon" v-if="!showPassword && !isRegister && formData.password.length"
                         @click="showPassword = !showPassword">
                      <use xlink:href="#icon-buxianshimima"></use>
                    </svg>
                    <el-button class="forgetPawBtn" @click.stop="toChangePawDialog">忘记密码</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <!--邮箱验证码input-->
              <el-form-item v-if="isRegister" prop="code">
                <el-input
                    type="text"
                    v-model="formData.code"
                    placeholder="请输入验证码"
                >
                  <template #prefix>
                    <svg class="icon">
                      <use xlink:href="#icon-yanzhengyanzhengma"></use>
                    </svg>
                  </template>
                  <template #suffix>
                    <el-button class="getCodeBtn"
                               :loading="getCodeBtn.isLoading"
                               :disabled="getCodeBtn.countDown>0"
                               @click.stop="getEmailCode($refs.form)">
                      {{ (getCodeBtn.countDown > 0 ? getCodeBtn.countDown : '') + ' 获取验证码' }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>

            </el-form>
            <div class="form-buttons">
              <div class="isLogin" v-if="!isRegister">
                <el-button class="register-btn" @click="userRegister">注册</el-button>
                <el-button :loading="loginBtnIsLoading" type="primary" class="login-btn"
                           @click="handleLogin($refs.form)">登录
                </el-button>
              </div>
              <el-button type="primary" :loading="registerBtnIsLoading" v-if="isRegister" class="register-and-login"
                         @click="handleRegister($refs.form)">登录/注册
              </el-button>
            </div>
            <div class="other-login">
              <span>其他登录:</span>
              <svg class="icon">
                <use xlink:href="#icon-qq"></use>
              </svg>
              <svg class="icon">
                <use xlink:href="#icon-weixin"></use>
              </svg>
              <svg class="icon">
                <use xlink:href="#icon-weibo"></use>
              </svg>
              <el-button class="cut-btn" link v-if="isRegister" @click="userRegister">密码登录</el-button>
              <el-button class="cut-btn" link v-if="!isRegister" @click="userRegister">验证码登录</el-button>
            </div>
          </div>

        </div>
        <div class="code-login">
          <p>扫码登录</p>
          <div class="QR-code">
            <img src="/public/img/qq.jpg">
          </div>
        </div>

      </div>
    </template>

    <template #footer>
      <div class="agreement">
        <span>注册登录即表示同意<a>用户协议</a>和<a>隐私政策</a></span>
      </div>
    </template>


  </el-dialog>
</template>

<script setup>
import {onMounted, ref} from "vue";
import {useAccountStore} from "@/store/accountStore.js";
import {checkEmailApi, loginApi, registerApi} from "@/api/loginApi.js";
import {getEmailCaptchaApi, getImgCaptchaApi} from "@/api/captchaApi.js";
import router from "@/router/router.js";
import {useUserStore} from "@/store/userStore.js";
import {ElMessage} from "element-plus";

let accountStore = useAccountStore();
let userStore = useUserStore();

//表单数据
let formData = ref({
  email: '529047508@qq.com',
  password: '111111',
  code: ''
})
let showPassword = ref(false)
let isRegister = ref(false)

/**
 * 登录/注册状态切换
 */
function userRegister() {
  isRegister.value = !isRegister.value
  formData.value = {
    email: '',
    password: '',
    code: ''
  }
}

/**
 * 获取邮箱验证码按钮状态控制
 */
let getCodeBtn = ref({
  isLoading: false,
  countDown: 0
})
/**
 * 获取邮箱验证码
 * @returns {Promise<void>}
 */
const getEmailCode = async form => {
  // 触发表单校验
  await form.validateField("email")
  try {
    getCodeBtn.value.isLoading = true
    let response = await getEmailCaptchaApi(formData.value.email, 0);
    ElMessage.success('验证码发送成功，请查看邮箱')
    await limitGetEmailCode()
  } finally {
    getCodeBtn.value.isLoading = false
  }
}
/**
 * 获取邮箱验证码倒计时
 */
const limitGetEmailCode = async () => {
  getCodeBtn.value.countDown = 10
  let id = setInterval(function () {
    if (getCodeBtn.value.countDown <= 0) {
      clearInterval(id)
    }
    getCodeBtn.value.countDown -= 1
  }, 1000)
}

/**
 * 验证码注册/登录
 */
let registerBtnIsLoading = ref(false)
const handleRegister = async (form) => {
  // 触发表单校验
  await form.validate()
  registerBtnIsLoading.value = true
  let response = await registerApi(formData.value);
  try {
    ElMessage.success("注册成功!")
    accountStore.showLoginDialog = false
    loginSuccess(response)
  } finally {
    registerBtnIsLoading.value = false
  }
}
/**
 * 密码登录
 */
let loginBtnIsLoading = ref(false)
const handleLogin = async (form) => {
  // 触发表单校验
  await form.validate()
  loginBtnIsLoading.value = true

  try {
    let response = await loginApi(formData.value)
    ElMessage.success('登陆成功')
    loginSuccess(response)
  } finally {
    loginBtnIsLoading.value = false
  }
}

/**
 * 登陆成功
 */
const loginSuccess = (response) => {
  console.log(response.data)
  userStore.userInfo = response.data
  accountStore.showLoginDialog = false
  //获取token
  localStorage.setItem("token", response.dataMap.token)
  router.push('/home')
}

/**
 * 邮箱格式校验
 * @param rules 校验规则
 * @param value 所校验的值
 * @param callback 校验后的回调
 */
const emailValidator = (rules, value, callback) => {
  const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
  if (!emailReg.test(value)) {
    return callback(new Error())
  }
  return callback()
}

/**
 * 表单校验规则
 */
const rules = ({
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {validator: emailValidator, message: "邮箱格式错误", trigger: "blur"}
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '验证码不能为空', trigger: "blur"}
  ]
})

/**
 * 打开忘记密码弹窗
 */
function toChangePawDialog(){
  accountStore.showLoginDialog = false
  accountStore.showChangePasswordDialog = true
}

/**
 * login-dialog关闭时的回调
 */
const handleClose = function () {
  formData.value = {
    email: '',
    password: '',
    code: ''
  }
  loginBtnIsLoading.value = false
  registerBtnIsLoading.value = false
}


/**
 * 获取图片验证码
 */
// let captchaImg = ref(null)
// let getImgCaptchaBtnIsLoading = ref(false)
// const getImgCaptcha = async () => {
//   //邮箱密码校验
//   await checkEmail()
//   checkPassword()
//
//   if (emailMessage.value === '' && passwordMessage.value === '') {
//     getImgCaptchaBtnIsLoading.value = true
//     try {
//       let response = await getImgCaptchaApi(formData.email);
//       // 将图片资源转为base64格式
//       captchaImg.value = 'data:image/png;base64,' + btoa(
//           new Uint8Array(response).reduce((data, byte) => data + String.fromCharCode(byte), '')
//       )
//     } finally {
//       getImgCaptchaBtnIsLoading.value = false
//     }
//   }
// }

</script>

<style lang="scss" scoped>
@import "@/styles/var";

.header {
  h1 {
    font-size: 20px;
    color: $color-black-text;
    padding-bottom: 1rem;
    border-bottom: 1px solid rgba(99, 99, 99, 0.2);
  }
}

.default {
  width: 100%;
  display: flex;

  .account-login {
    width: 60%;
    border-right: 1px solid rgba(99, 99, 99, 0.2);

    header {
      font-size: 1rem;
      padding: 0 1rem;
    }
  }

  .code-login {
    width: 40%;
  }
}

.login-form {
  padding: 1rem;
  color: $color-black-text;

  :deep(.el-input__wrapper) {
    box-shadow: none;
    background-color: #f2f3f5;
    height: 2.5rem;
  }

  :deep(.el-input__wrapper:has(.el-input__inner:focus)) {
    box-shadow: 0 0 0 1px #409eff inset;
    background-color: transparent;
  }

  .getCodeBtn, .forgetPawBtn {
    background-color: transparent;
    border: none;
  }

  .icon {
    font-size: 1.2rem;
    cursor: pointer;
    z-index: 100;
  }

}

.form-buttons {
  padding: 1rem 0;

  .isLogin {
    display: flex;
    justify-content: space-between;

    button {
      height: 40px;
      width: 130px;
      cursor: pointer;
    }

    .register-btn {
      background-color: #e8f2ff;
      color: $color-deep-theme;
      box-shadow: 0 0 0 1px rgba(51, 126, 204, 0.5);
    }
  }

  .register-and-login {
    height: 40px;
    width: 100%;
  }

}

.other-login {
  position: relative;

  .icon {
    margin-left: 0.5rem;
  }

  .cut-btn {
    position: absolute;
    right: 0;
  }
}

.code-login {
  display: flex;
  flex-direction: column;
  align-items: center;

  img {
    width: 200px;
    height: 200px;
    object-fit: cover;
    border: 1px solid rgba(99, 99, 99, 0.2);
    margin: 1rem;
  }
}

.agreement {
  display: flex;
  justify-content: center;
}
</style>